package com.ddaqq.shop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
public class JsonController {
    private static String Password = "5gl()$=z)C?z97&PqzK#h6GiPuYXl<Ny";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/")
    public String usage() {
        return "GET /keyJsonMap?key={}" +
                "<br>\n    " +
                "POST /keyJsonMap?key={}    {...}" +
                "<br>\n    " +
                "POST /newKey    {\"password\":{},\"key\":{}}" +
                "<br>\n    " +
                "GET /list";
    }

    @PostMapping("/newKey")
    public String newKey(@RequestBody SafeNewKey form) {
        if (form == null) {
            return "(error) null form";
        }
        if (form.getKey() == null) {
            return "(error) null form.key";
        }
        if (form.getPassword() == null) {
            return "(error) null form.password";
        }
        if (Password.equals(form.getPassword())) {
            redisTemplate.opsForValue().set(form.getKey(), "");
            return "OK";
        } else {
            return "(error) password not valid";
        }
    }

    @PostMapping("/keyJsonMap")
    public String send(@RequestParam(required = false) String key,
                       @RequestBody(required = false) String body) {
        if (key == null) {
            return "(error) null key";
        }
        if (body == null) {
            return "(error) null body";
        }
        // 这里可以使用set if exist 来控制安全
        if (redisTemplate.opsForValue().setIfPresent(key, body)) {
            return "OK";
        } else {
            return "(null)";
        }
    }

    @GetMapping(value = "/keyJsonMap")
    public String receive(@RequestParam(required = false) String key) {
        if (key == null) {
            return "(error) null key";
        }
        String s = redisTemplate.opsForValue().get(key);
        if (s == null) {
            return "(null)";
        }
        return s;
    }
    @GetMapping("/list")
    public Set<String> list(){
        return redisTemplate.keys("*");
    }
}
